package online.lmds.sdmanage.main.authentication.service;

import com.sun.org.apache.regexp.internal.RE;
import online.lmds.sdmanage.common.Constants;
import online.lmds.sdmanage.common.Status;
import online.lmds.sdmanage.common.entity.Result;
import online.lmds.sdmanage.common.utils.DataFormatUtils;
import online.lmds.sdmanage.common.utils.MessageDigestUtils;
import online.lmds.sdmanage.common.utils.RandomGenerateUtils;
import online.lmds.sdmanage.main.authentication.AuthConsts;
import online.lmds.sdmanage.main.authentication.dao.UserDao;
import online.lmds.sdmanage.main.authentication.entity.User;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * Created by Brighten Ma on 2017/4/10.
 * 用户
 */

@Service("UserService")
public class UserServiceImpl implements UserService {

    @Resource(name = "UserDao")
    private UserDao userDao;


    private void handle(User user) {

        // TODO: 2017/4/15
    }

    @Override
    public Result regAddUser(User user) {
        Result result = new Result();

        if (!DataFormatUtils.isUsername(user.getUserName())) {
            return result.setErrorCode().setStatus(Status.REG_NAME_ERROR)
                    .setMessage(Status.REG_NAME_ERROR.msg);
        }

        if (!DataFormatUtils.isPassword(user.getPassword(), AuthConsts.MIN_PASSWORD_LENGTH)) {
            return result.setErrorCode().setStatus(Status.FORMAT_PASSWORD_ERROR);
        }


        //验证用户名是否已使用
        User oldUser = getByName(user);
        if (oldUser != null) {
            return result.setErrorCode().setStatus(Status.REG_NAME_REPEAT);
        }
        //原始密码
        String psw = user.getPassword();
        user.setPassword(MessageDigestUtils.getSHA1(user.getPassword(), AuthConsts.SALT));
        user.setUid(UUID.randomUUID().toString());
        userDao.regAddUser(user);
        user.setPassword(psw);
        return login(user);
    }

    @Override
    public Result login(User user) {

        Result result = userCheck(user);

        if (result.isError()) {
            return result;
        }

        // FIXME: 2017/4/15  just test  user
        if (!user.getUserName().equals("mgm") && !user.getUserName().equals("my")) {
            user.setPassword(MessageDigestUtils.getSHA1(user.getPassword(), AuthConsts.SALT));
        }
        User getUser = userDao.getByLogin(user);
        if (getUser == null) {
            return result.setErrorCode().setStatus(Status.AUTH_USER_PASSWORD_ERROR);
        }

        // token未过期，给token续期；token已过期，更新token
        int effectiveRows = 0;
        System.out.println("getUser.getToken() = "+ getUser.getToken());
        System.out.println("getUser.getTokenExp() = "+ getUser.getTokenExp().getTime());
        System.out.println("System.currentTimeMillis() = "+ System.currentTimeMillis());
        if (!StringUtils.isEmpty(getUser.getToken()) && getUser.getTokenExp() != null
                && getUser.getTokenExp().getTime() >= System.currentTimeMillis()) {
            getUser.setTokenExp(new Date(System.currentTimeMillis() + AuthConsts.TOKEN_VALID_TIME));
            effectiveRows = userDao.updateTokenExpiryTimeById(getUser);
            System.out.println("token 未过期");
        } else {
            getUser.setToken(RandomGenerateUtils.generateToken(getUser.getPhone()));
            getUser.setTokenExp(new Date(System.currentTimeMillis() + AuthConsts.TOKEN_VALID_TIME));
            effectiveRows = userDao.updateTokenById(getUser);
            System.out.println("token 已过期");
        }

        if (effectiveRows != 1) {
            return result.setErrorCode().setStatus(Status.AUTH_TOKEN_UPDATE_ERROR);
        }

        if (user.getLoginDeviceUid() != null){
            user.setId(getUser.getId());
            userDao.updateById(user);
        }

            return result.setSuccessCode().setStatus(Status.SUCCEED).setData(getUser);
    }

    @Override
    public Result save(User user) {

        Result result = new Result();

        if (!DataFormatUtils.isUsername(user.getUserName())) {
            return result.setErrorCode().setStatus(Status.REG_NAME_ERROR)
                    .setMessage(Status.REG_NAME_ERROR.msg);
        }

        if (!DataFormatUtils.isPassword(user.getPassword(), AuthConsts.MIN_PASSWORD_LENGTH)) {
            return result.setErrorCode().setStatus(Status.FORMAT_PASSWORD_ERROR);
        }

        //原始密码
        String psw = user.getPassword();

        userDao.save(user);
        user.setPassword(psw);
        return login(user);
    }

    @Override
    public Result getByToken(User user) {
        Result result = new Result();
        User getUser = userDao.getByToken(user);
        if (getUser == null) {
            return result.setErrorCode().setMessage("请登录").setStatus(Status.AUTH_TOKEN_REEOR);
        }
        if (getUser.getTokenExp().getTime() < System.currentTimeMillis()) {
            return result.setErrorCode().setMessage("登陆身份过期").setStatus(Status.AUTH_TOKEN_EXPIRED);
        }

        getUser.setTokenExp(new Date(System.currentTimeMillis() + AuthConsts.TOKEN_VALID_TIME));
        userDao.updateTokenExpiryTimeById(getUser);

        return result.setSuccessCode().setStatus(Status.SUCCEED).setData(getUser);
    }

    @Override
    public User getByName(User user) {
        return userDao.getByName(user);
    }

    @Override
    public Result updateById(User e) {
        // headImgUrl, nickName, gender, email, education, residence
        Result result = new Result();
        if (e.getUserId() == null) {
            return result.setErrorCode().setMessage("请先登录").setStatus(Status.BASE_NEED_LOGIN);
        }
        if (StringUtils.isEmpty(e.getNickName())) {
            e.setNickName(null);
        } else if (!DataFormatUtils.isNickName(e.getNickName())) {
            return result.setErrorCode().setMessage("昵称中只允许使用汉字，字母，数字，下划线，负号").setStatus(Status.FORMAT_NICK_ERROR
            );
        }
        Integer gender = e.getGender();
        if (gender != null && gender != Constants.GENDER_FEMALE && gender != Constants.GENDER_MALE) {
            return result.setErrorCode().setMessage("请选择正确的性别").setStatus(Status.FORMAT_GENDER_ERROR);
        }
        if (StringUtils.isEmpty(e.getEmail())) {
            e.setEmail(null);
        } else if (!e.getEmail().contains("@")) {
            return result.setErrorCode().setMessage("请输入正确的邮箱").setStatus(Status.FORMAT_EMAIL_ERROR);
        }


        if (StringUtils.isEmpty(e.getHeadImgUrl())) {
            e.setHeadImgUrl(null);
        }

//        else if (!checkImgUrl(e)) {
//            return result.setErrorCode().setMessage("请勿修改上传的图片URL").setStatus(Status.base_file_path_err);
//        }


        int rows = userDao.updateById(e);
        if (rows != 1) {
            return result.setErrorCode().setMessage("更新资料失败").setStatus(Status.USER_UPDETE_ERROR);
        } else {
            return result.setSuccessCode().setMessage("success");
        }
    }

    @Override
    public Result updatePassword(User e) {
        // password, oldPassword, token
        Result result = new Result();
        String pwd = e.getPassword();
        String old = e.getOloPassword();
        if (e.getUserId() == null) {
            return result.setErrorCode().setMessage("请先登录").setStatus(Status.BASE_NEED_LOGIN);
        }
        if (pwd == null || old == null || pwd.length() < AuthConsts.MIN_PASSWORD_LENGTH
                || old.length() < AuthConsts.MIN_PASSWORD_LENGTH) {
            return result.setErrorCode().setMessage(String.format("密码长度应不小于%d位", AuthConsts.MIN_PASSWORD_LENGTH)).setStatus(Status.FORMAT_PASSWORD_ERROR);
        }
        if (!DataFormatUtils.isPassword(pwd, AuthConsts.MIN_PASSWORD_LENGTH)
                || !DataFormatUtils.isPassword(old, AuthConsts.MIN_PASSWORD_LENGTH)) {
            return result.setErrorCode().setMessage("密码中请勿使用中文和空格").setStatus(Status.FORMAT_PASSWORD_ERROR);
        }
        e.setPassword(MessageDigestUtils.getSHA1(pwd, AuthConsts.SALT));
        e.setOloPassword(MessageDigestUtils.getSHA1(old, AuthConsts.SALT));
        int rows = userDao.updatePassword(e);
        if (rows != 1) {
            return result.setErrorCode().setMessage("修改密码失败，请检查token或原密码").setStatus(Status.AUTH_USER_PASSWORD_ERROR);
        } else {
            return result.setSuccessCode().setMessage("success");
        }
    }

    @Override
    public Result updatePasswordByPhone(User e) {
        return null;
    }

    @Override
    public Result quickLogin(User e) {
        return null;
    }


    @Override
    public Result userCheck(User user) {
        Result result = new Result();

        String password = user.getPassword();
        if (password == null || password.length() < AuthConsts.MIN_PASSWORD_LENGTH) {
            return result.setErrorCode().setStatus(Status.FORMAT_PASSWORD_ERROR);
        }
        return result.setSuccessCode();
    }


}
